import i18n from '@/locales'
import axios from 'axios'
import { Toast } from 'vant'
import router from '@/router'
axios.defaults.baseURL = process.env.VUE_APP_BASE_API
axios.defaults.responseType = 'json'
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest'
axios.defaults.timeout = 3 * 60 * 1000
import { getToken } from '@/utils/auth'
import { Encrypt } from '@/utils/cryptoJS'
import passAuth from '@/utils/passAuth'
import noEncty from '@/utils/noEncry'
import store from '@/store'
import whiteAPIs from '@/utils/whiteAPIs'
let isNeedLogin = false
const errHandle = (error) => {
  Toast.fail(
    error && error.msg ? error.msg : i18n.t('用户未登录或会话已失效,请重新登录')
  )
  store.dispatch('resetState')
  store.commit('user/SET_TOKEN', '')
  router.push({ path: '/login' })
}

const errNoAccess = (data) => {
  if (data.data.msg) {
    Toast.fail(data.data.msg)
  } else {
    Toast.fail(i18n.t('抱歉，您没有权限！'))
  }
}
const getPublicQueryData = (number) => {
  var arr = new Array()
  var arr1 = new Array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
  var nonceStr = ''
  for (var i = 0; i < number; i++) {
    var n = Math.floor(Math.random() * 10)
    arr[i] = arr1[n]
    nonceStr += arr1[n]
  }
  return {
    uuid: nonceStr,
    timestamp: new Date().getTime() + '',
  }
}

axios.interceptors.request.use(
  (config) => {
    const rAuth = getToken()
    const isPassAuth = passAuth.find((it) => {
      return it === config.url
    })
    if (!isPassAuth) {
      // 添加请求头
      if (rAuth) {
        config.headers.common['aioSsoTokenId'] = rAuth
        config.headers.common['ucSsoTokenId'] = rAuth
      }
    }
    config.headers.common['from'] = 'saas'
    config.headers.common['ucSystemFlag'] = 31
    // config.headers.common['ucClientType'] = 7
    config.headers.common['lang'] = localStorage.getItem('contract-tenant-h5-lang') || 'zh-CN';

    const isProduction = ['production', 'prod'].includes(
      process.env.VUE_APP_NODE_ENV
    )
    if (
      config.method == 'post' &&
      isProduction &&
      noEncty.indexOf(config.url) == -1
    ) {
      let queryData = {
        ...(config.data || {}),
        ...getPublicQueryData(10),
      }
      config.data = {
        encryParam: Encrypt(JSON.stringify(queryData)),
      }
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

axios.interceptors.response.use(
  (response) => {
    if (axios.isCancel(response)) {
      console.log('Request canceled', response.message)
    }
    if (whiteAPIs.includes(response.config.url)) {
      return response
    }
    if (response.data.resultCode && response.data.resultCode !== '0000') {

      return Promise.reject({
        code: '500',
        data: response.data,
      })
    }

    if (
      response.data &&
      response.data.data &&
      response.data.data.resultCode &&
      response.data.data.resultCode !== '0000' &&
      Number(response.data.data.resultCode) !== 200
    ) {
      // 发布运单resultCode为2222的时候不弹提示消息  1003合同签署页面没有权限不报错展示弹窗
      let noErrorTipCode = [
        '1001',
        '1002',
        '2222',
        '1001',
        '3027',
        '3028',
        '3029',
        '1003',
        '3333',
      ]
      if (noErrorTipCode.indexOf(response.data.data.resultCode) !== -1) {
        return Promise.reject({
          ...response.data,
          noErrorTip: true,
        })
      }
      return Promise.reject(response.data)
    }
    if (
      response.data &&
      response.data.code == '401' &&
      window.location.pathname !== '/login' &&
      !isNeedLogin
    ) {
      errHandle(response.data)
      return
    }

    if (
      response.data &&
      response.data.code == 'AIO-401' &&
      window.location.pathname !== '/login' &&
      !isNeedLogin
    ) {
      errHandle()
      return
    }
    if (
      response.data &&
      response.data.code &&
      response.data.code != 200 &&
      response.data.code !== '0000'
    ) {
      if (
        response.config.url == '/scm-oms-web-server/front/shop/cancelShop' &&
        response.data.code == '600'
      ) {
        return Promise.reject({
          ...response.data,
          noErrorTip: true,
        })
      } else if (
        (response.data && response.data.code == '1001') ||
        (response.data && response.data.code == '601')
      ) {
        return Promise.reject({
          ...response.data,
          noErrorTip: true,
        })
      } else {
        return Promise.reject(response.data)
      }
    }

    if (
      response.data &&
      (response.data.code == '200' || response.data.resultCode == '0000')
    ) {
      return response
    }
    if (response.status >= 200 && response.status < 300) {
      localStorage.setItem('tokenEffective', 'effective')
      return response
    }

    return Promise.reject(response.data)
  },
  (error) => {
    if (error.response) {
      if (error.response.status === 403) {
        errNoAccess(error.response)
        return
      }
      if (
        error.response.status === 401 &&
        window.location.pathname !== '/login' &&
        !isNeedLogin
      ) {
        errHandle()
        return
      }
      // response 返回 status 为401 并且 当切页面不是登录页面 并且 抛出错误统计 为0 时，提示token 异常，重新登录
      if (
        error.response.data.code === 'AIO-401' &&
        window.location.pathname !== '/login' &&
        !isNeedLogin
      ) {
        errHandle()
        return
      }
    }
    let errorData = {}
    if (error.response && error.response.data) {
      errorData = error.response.data
    }
    return Promise.reject(errorData)
  }
)
const service = {
  successHandler(res) {
    if (res.status === 200) {
      if (res.data.code == '200'||res.data.resultCode == '0000') {
        return res.data
      } else {
        Toast.fail(res.data.msg || res.data.message || i18n.t('接口非200'))
        // 401返回登录
        if (res.data.code == '401') {
          store.dispatch('resetState')
          store.commit('user/SET_TOKEN', '')
          router.push({ path: '/login' })
        }
      }
    }
    return {}
  },
  errHandler(err, { errHandler = true }) {
    if (
      errHandler &&
      err.code &&
      err.code !== 'AIO-401' &&
      err.status !== 401
    ) {
      if (err.data) {
        if (!err.noErrorTip) {
          Toast.fail(
            err.data.resultMsg || err.message || i18n.t('接口调用异常')
          )
        }
      } else {
        if (err.code === '301') {
          return err
        }
        if (!err.noErrorTip) {
          Toast.fail(err.msg || err.message || i18n.t('接口调用异常'))
        }
      }
    }

    return err
  },
  get(url, options, otherConfig = {}) {
    return axios
      .get(url, {
        params: options,
        ...otherConfig,
      })
      .then(this.successHandler)
      .catch((err) => this.errHandler(err, otherConfig))
  },
  download(url, params) {
    return axios
      .get(url, {
        responseType: 'blob',
        params,
      })
      .then((e) => {
        return e
      })
      .catch((err) => this.errHandler(err))
  },
  post(url, options, otherConfig = {}) {
    return axios
      .post(url, options, otherConfig)
      .then(this.successHandler)
      .catch((err) => this.errHandler(err, otherConfig))
  },
  delete(url, options, otherConfig = {}) {
    return axios
      .delete(url, {
        data: options,
        ...otherConfig,
      })
      .then(this.successHandler)
      .catch((err) => this.errHandler(err, otherConfig))
  },
  deleteParams(url, options, otherConfig = {}) {
    return axios
      .delete(url, {
        params: options,
        ...otherConfig,
      })
      .then(this.successHandler)
      .catch((err) => this.errHandler(err, otherConfig))
  },
  put(url, options, otherConfig = {}) {
    return axios
      .put(url, options, otherConfig)
      .then(this.successHandler)
      .catch((err) => this.errHandler(err, otherConfig))
  },
  postExport(url, param) {
    return axios
      .post(url, param, {
        responseType: 'blob',
        headers: {
          'Airport-Token': localStorage.getItem('token'),
        },
      })
      .then((response) => {
        const newfileName =
          response.headers['content-disposition'].split('=')[1]
        const decodeName = decodeURI(newfileName)
        if ('download' in document.createElement('a')) {
          const aLink = document.createElement('a')
          const blob = new Blob([response.data], {
            type: 'application/vnd.ms-excel',
          })
          aLink.href = URL.createObjectURL(blob)
          aLink.setAttribute('download', `${decodeName}`)
          aLink.click()
          window.URL.revokeObjectURL(blob)
        } else {
          // IE10+下载
          const blob = new Blob([response.data]) // 这个content是下载的文件内容
          navigator.msSaveBlob(blob, decodeName)
        }
      })
      .catch((error) => {
        console.error(error)
      })
  },
  getExport(url, param) {
    return axios
      .get(
        url,
        { params: param },
        {
          responseType: 'blob/json',
        }
      )
      .then((response) => {
        const newfileName =
          response.headers['content-disposition'].split('=')[1]
        const decodeName = decodeURI(newfileName)
        if ('download' in document.createElement('a')) {
          const aLink = document.createElement('a')
          const blob = new Blob([response.data], {
            type: 'application/vnd.ms-excel',
          })
          aLink.href = URL.createObjectURL(blob)
          aLink.setAttribute('download', `${decodeName}`)
          aLink.click()
          window.URL.revokeObjectURL(blob)
        } else {
          // IE10+下载
          const blob = new Blob([response.data]) // 这个content是下载的文件内容
          navigator.msSaveBlob(blob, decodeName)
        }
      })
      .catch((error) => {
        console.error(error)
      })
  },
  postExcelExport(url, param) {
    return axios
      .post(url, param, {
        responseType: 'blob',
      })
      .then((response) => {
        const decodeName = decodeURI(param.fileName)
        if ('download' in document.createElement('a')) {
          const aLink = document.createElement('a')
          const blob = new Blob([response.data], {
            type: 'application/vnd.ms-excel',
          })
          aLink.href = URL.createObjectURL(blob)
          aLink.setAttribute('download', `${decodeName}`)
          aLink.click()
          window.URL.revokeObjectURL(blob)
        } else {
          // IE10+下载
          const blob = new Blob([response.data]) // 这个content是下载的文件内容
          navigator.msSaveBlob(blob, decodeName)
        }
      })
      .catch((error) => {
        console.error(error)
      })
  },
  getExportExcel(url, param, otherConfig = {}) {
    const params = param
    return axios({
      url: url,
      method: 'get',
      responseType: 'blob',
      params: params,
      ...otherConfig,
    })
      .then((response) => {
        // const newfileName = response.headers['content-disposition'].split('=')[1]
        const newfileName = param.fileName
        const decodeName = decodeURI(newfileName)
        if ('download' in document.createElement('a')) {
          const aLink = document.createElement('a')
          const blob = new Blob([response.data], {
            type: 'application/vnd.ms-excel',
          })
          aLink.href = URL.createObjectURL(blob)
          aLink.setAttribute('download', `${decodeName}`)
          aLink.click()
          window.URL.revokeObjectURL(blob)
        } else {
          // IE10+下载
          const blob = new Blob([response.data]) // 这个content是下载的文件内容
          navigator.msSaveBlob(blob, decodeName)
        }
      })
      .catch((error) => {
        Toast.fail(error)
      })
  },
}

export default service
